package com.hd.trans.network

import android.util.ArrayMap
import android.util.Log
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.hd.trans.TranslationInterior
import com.hd.trans.network.bean.UserInfoBean
import com.hd.trans.share.GsonTypeAdapter
import com.hd.trans.share.Md5Util
import com.hd.trans.ui.base.AppContextProvider
import com.hd.trans.utils.CommonUtil
import com.hd.trans.utils.DeviceUtil
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.TreeMap

object ParamUtils {

    private val gson: Gson by lazy {
        GsonBuilder().registerTypeAdapter(object : TypeToken<TreeMap<String?, Any?>?>() {}.type, GsonTypeAdapter()).create()
    }
    fun toJson(data: Any): Any {

        var isString = data is String

        Log.d("TAG", "toJson() called with: data = $data-----$isString")

        return when (data) {
            is Long -> data
            is String -> data
            is Int -> data
            is Boolean -> data
            is Float -> data.toFloat()
            is Double -> data.toDouble()
            else -> gson.toJson(data)
        }
    }

    private fun secretData(data: TreeMap<String, Any>): RequestBody {
        var jsonBuild = StringBuilder()
        data.forEach {
            if (it.key != "fileopenpwd") {
                jsonBuild.append("&").append(it.key).append("=").append(toJson(it.value))
            }
        }
        jsonBuild.deleteCharAt(0)
        jsonBuild.append("hUuPd20171206LuOnD")
        Log.d("secretData", "secretData() called with: data = $jsonBuild")
        var datasign = Md5Util.getMD5(jsonBuild.toString())

        data["datasign"] = datasign
        val json = gson.toJson(data)

        return json.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
    }


    fun <T : Any> toRequestBody(data: T): RequestBody {
        val json = gson.toJson(data)
        var map: TreeMap<String, Any> = gson.fromJson(json,
            object : TypeToken<TreeMap<String, Any>>() {}.type)
        return secretData(map)
    }

    fun createAiTransParams(params: ArrayMap<String, Any>, userinfoBean: UserInfoBean? = null): RequestBody {
        val arguments: MutableMap<String, Any> = HashMap()
        params.forEach {
            arguments.put(it.key, it.value)
        }
        // 是否显示转换后的文字内容，只对转换后为txt类型的功能起作用，取值范围为(0,1,2)；默认为0
        arguments["productinfo"] = TranslationInterior.getProductInfo()
        arguments["deviceid"] = DeviceUtil.getDeviceId(AppContextProvider.getContext())
        arguments["devicetype"] = "android"
        if (userinfoBean != null) {
            if(userinfoBean.username.isNotEmpty()){
                arguments["account"] = userinfoBean.username
            }
            if (userinfoBean.usertoken.isNotEmpty()){
                arguments["usertoken"] = userinfoBean.usertoken
            }
        }
        arguments["timestamp"] = PreferenceMgr.getInstance().serverTimeStamp/1000
        return toRequestBody(arguments)
    }

    fun createText2VoiceParams(params: ArrayMap<String, Any>, userinfoBean: UserInfoBean? = null): RequestBody {

        val arguments: MutableMap<String, Any> = TreeMap { obj1, obj2 -> // 按照key的升序排序
            obj1?.compareTo(obj2!!)!!
        }
        params.forEach {
            arguments[it.key] = it.value
        }
        // 是否显示转换后的文字内容，只对转换后为txt类型的功能起作用，取值范围为(0,1,2)；默认为0
        arguments["productinfo"] = TranslationInterior.getProductInfo()
        arguments["deviceid"] = DeviceUtil.getDeviceId(AppContextProvider.getContext())
        if (userinfoBean != null) {
            if(userinfoBean.username.isNotEmpty()){
                arguments["account"] = userinfoBean.username
            }
            if (userinfoBean.usertoken.isNotEmpty()){
                arguments["usertoken"] = userinfoBean.usertoken
            }
        }
        val timeStampSec = CommonUtil.getServiceTimeStamp()
        val timestamp = String.format("%010d", timeStampSec)
        arguments["timestamp"] = timestamp
        return toRequestBody(arguments)
    }

    fun createText2SpeechParams(params: ArrayMap<String, Any>): RequestBody {

        val arguments: MutableMap<String, Any> = TreeMap { obj1, obj2 -> // 按照key的升序排序
            obj1?.compareTo(obj2!!)!!
        }
        params.forEach {
            arguments[it.key] = it.value
        }
        return toRequestBody(arguments)
    }

}